<template>
	<view class="container">
		
		<!-- 维修方式的选择  0到店维修 1上门取车-->
		<view class="repair-type">
			<text class="type-label">维修方式</text>
			<radio-group class="radio-group" @change="handleRepairTypeChange">
				<radio class="radio-item" :value="'0'" :checked="repairType === '0'">到店维修</radio>
				<radio class="radio-item" :value="'1'" :checked="repairType === '1'">上门取车</radio>
			</radio-group>
		</view>

		<!-- 客户信息 动态表单 -->
		<view class="info-section">
			<text class="section-title">客户信息</text>
			<view class="from-item">
				<text class="label">车主姓名</text>
				<input type="text" v-model="ownerName" placeholder="请输入预约车主姓名" />
			</view>

			<view class="from-item">
				<text class="label">联系方式</text>
				<input type="text" v-model="phone" placeholder="请输入联系方式" />
			</view>

			<view class="from-item">
				<text class="label">预约时间</text>
				<view class="datetime-picker">
					<uni-datetime-picker type="datetime" returnType="date" v-model="bookingDate" @change="changeLog" />
				</view>
			</view>

			<view class="from-item" v-if="repairType === '1'">
				<text class="label">取车位置</text>
				<uni-easyinput class="uni-mt-5" suffixIcon="location" v-model="position" placeholder="请选择取车位置"
					@iconClick="choosePosition"></uni-easyinput>
			</view>
			<!-- 全屏地图容器 -->
			<view class="fullscreen-map-container" v-if="this.isChoosingPosition===true">
				<map 
					id="fullscreenMap"
					class="fullscreen-map"
					:latitude="mapCenter.latitude" 
					:longitude="mapCenter.longitude"
					:scale="16"
					:markers="markers"
					:show-location="true"
					@tap="onMapTap"
					@regionchange="onRegionChange"
				></map>
				
				<!-- 取消按钮 -->
				<view class="map-cancel-btn">
					<button class="cancel-btn" @click="cancelPosition">取消选择</button>
				</view>
				
				<!-- 提示信息 -->
				<view class="map-tip">
					点击地图选择位置
				</view>
			</view>
		</view>

		<!-- 表单信息 固定表单 -->
		<view class="info-section">
			<text class="section-title">车辆信息</text>
			<view class="from-item">
				<text class="label">车辆类型</text>
				<uni-data-picker placeholder="请选择车辆类型" popup-title="请选择车辆品牌" :localdata="dataTree" v-model="model"
					@change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened"
					@popupclosed="onpopupclosed">
				</uni-data-picker>
			</view>

			<view class="from-item">
				<text class="label">车牌号码</text>
				<input type="text" v-model="vehicleNumber" placeholder="请输入车牌号" />
			</view>
		</view>

		<!-- 照片上传 固定区域 -->
		<view class="photo-section">
			<text class="section-title">照片</text>
			<view class="photo-item">
				<text class="photo-label">整车照片</text>
				<uni-file-picker limit="3" ref="wholeCar"></uni-file-picker>
			</view>
			<view class="photo-item">
				<view class="photo-label">维修部位</view>
				<uni-file-picker limit="6" ref="repairCar"></uni-file-picker>
			</view>

			<!-- 提交按钮 -->
			<button class="submit-btn" @click="submitForm">提交</button>
		</view>
	</view>
</template>

<script>
	import { reverseGeocode, getCurrentLocation } from '@/utils/mapService.js'
	
	export default {
		data() {
			return {
				isChoosingPosition: false, // 地图选择状态
				selectedLngLat: null, // 选中的经纬度
				mapCenter: {
					latitude: 39.908823, // 默认北京坐标
					longitude: 116.397470
				},
				currentMapCenter: {
					latitude: 39.908823,
					longitude: 116.397470
				},
				markers: [], // 地图标记点
				repairType: '0', // 默认到店维修
				ownerName: '',
				phone: '',
				bookingDate: '',
				position: '',
				model: '', // 用于uni-data-picker的双向绑定
				dataTree: [{
						text: "油车",
						value: "1-0",
						children: [{
								text: "大众",
								value: "1-1"
							},
							{
								text: "奥迪",
								value: "1-2"
							},
							{
								text: "其他车辆",
								value: "1-3"
							}
						]
					},
					{
						text: "新能源",
						value: "2-0",
						children: [{
								text: "比亚迪",
								value: "2-1"
							},
							{
								text: "特斯拉",
								value: "2-2"
							},
							{
								text: "小米",
								value: "2-3"
							},
							{
								text: "其他车辆",
								value: "2-4"
							}
						]
					}
				],
				vehicleNumber: '',

			};
		},
		
		methods: {
			
			handleRepairTypeChange(e) {
				// 处理radio选中值变化，更新repairType
				this.repairType = e.detail.value;
			},
			changeLog(e) {
				// 处理日期时间选择变化
				console.log('日期时间改变:', e.detail.value);
			},
			onchange(e) {
				// 处理uni-data-picker选择变化
				console.log('选择变化:', e.detail);
			},
			onnodeclick(e) {
				// 处理uni-data-picker节点点击
				console.log('节点点击:', e.detail);
			},
			onpopupopened() {
				// 处理uni-data-picker弹窗打开
				console.log('弹窗打开');
			},
			onpopupclosed() {
				// 处理uni-data-picker弹窗关闭
				console.log('弹窗关闭');
			},
			choosePosition(){
				this.isChoosingPosition = true;
				// 获取当前位置作为地图中心
				this.getCurrentPosition();
			},
			
			// 地图点击事件 - 单击选择位置并自动解析地址
			async onMapTap(e) {
				// 使用当前地图中心位置作为点击位置
				const latitude = this.currentMapCenter.latitude;
				const longitude = this.currentMapCenter.longitude;
				
				// 选择位置并解析地址
				await this.selectPosition(latitude, longitude);
			},
			
			// 选择位置并解析地址
			async selectPosition(latitude, longitude) {
				this.selectedLngLat = { latitude, longitude };
				
				// 更新地图标记
				this.markers = [{
					id: 1,
					latitude: latitude,
					longitude: longitude,
					title: '选择的位置',
					iconPath: '/static/logo.png',
					width: 30,
					height: 30
				}];
				
				// 更新地图中心到点击位置
				this.mapCenter = { latitude, longitude };
				
				// 自动进行地址解析
				await this.reverseGeocodePosition(latitude, longitude);
			},
			
			// 地图区域变化事件
			onRegionChange(e) {
				// 更新当前地图中心位置
				if (e.detail && e.detail.centerLocation) {
					this.currentMapCenter = {
						latitude: e.detail.centerLocation.latitude,
						longitude: e.detail.centerLocation.longitude
					};
				}
			},
			
			// 获取当前位置
			async getCurrentPosition() {
				try {
					uni.showLoading({
						title: '定位中...'
					});
					
					const location = await getCurrentLocation();
					if (location.success) {
						this.mapCenter = {
							latitude: location.latitude,
							longitude: location.longitude
						};
						this.currentMapCenter = {
							latitude: location.latitude,
							longitude: location.longitude
						};
					} else {
						uni.showToast({
							title: '定位失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取位置失败:', error);
					uni.showToast({
						title: '定位失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			
			// 地址逆解析
			async reverseGeocodePosition(latitude, longitude) {
				let isLoading = false;
				
				try {
					const lat = parseFloat(latitude);
					const lng = parseFloat(longitude);
					
					if (isNaN(lat) || isNaN(lng)) {
						throw new Error('经纬度格式错误');
					}
					
					uni.showLoading({
						title: '解析地址中...'
					});
					isLoading = true;
					
					const result = await reverseGeocode(lat, lng);
					
					if (result.success) {
						this.position = result.address;
						this.isChoosingPosition = false;
						uni.showToast({
							title: '位置选择成功',
							icon: 'success'
						});
					} else {
						// 解析失败，使用坐标作为地址
						this.position = `经度:${lng.toFixed(6)}, 纬度:${lat.toFixed(6)}`;
						this.isChoosingPosition = false;
						uni.showToast({
							title: '地址解析失败，已使用坐标',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('地址解析失败:', error);
					// 发生错误时，使用坐标作为地址
					const lat = parseFloat(latitude);
					const lng = parseFloat(longitude);
					if (!isNaN(lat) && !isNaN(lng)) {
						this.position = `经度:${lng.toFixed(6)}, 纬度:${lat.toFixed(6)}`;
					} else {
						this.position = '位置选择失败';
					}
					this.isChoosingPosition = false;
					uni.showToast({
						title: '地址解析失败，已使用坐标',
						icon: 'none'
					});
				} finally {
					if (isLoading) {
						uni.hideLoading();
					}
				}
			},
			
			// 取消选择位置
			cancelPosition() {
				this.isChoosingPosition = false;
				this.selectedLngLat = null;
				this.markers = [];
			},
			submitForm() {
				// 表单校验
				if (!this.ownerName) {
					uni.showToast({
						title: '请输入预约车主姓名',
						icon: 'none',
					});
					return;
				}
				if (!this.phone) {
					uni.showToast({
						title: '请输入联系方式',
						icon: 'none',
					});
					return;
				}
				if (!this.bookingDate) {
					uni.showToast({
						title: '请选择预约时间',
						icon: 'none',
					});
					return;
				}
				if (this.repairType == 1) {
					if (!this.position) {
						uni.showToast({
							title: '请输入上门取车地址',
							icon: 'none',
						});
						return;
					}
				}
				if (!this.model) {
					uni.showToast({
						title: '请选择车辆类型',
						icon: 'none',
					});
					return;
				}
				if (!this.vehicleNumber) {
					uni.showToast({
						title: '请输入车牌号',
						icon: 'none',
					});
					return;
				}
				const wholeCarFiles = this.$refs.wholeCar.files || [];
				const repairPartFiles = this.$refs.repairCar.files || [];
				if (wholeCarFiles.length === 0) {
					uni.showToast({
						title: '请上传整车照片',
						icon: 'none',
					});
					return;
				}
				if (repairPartFiles.length === 0) {
					uni.showToast({
						title: '请上传维修部位照片',
						icon: 'none',
					});
					return;
				}
				uni.showModal({
					title: '提交',
					content: '确认是否提交？',
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '提交成功',
								icon: 'success',
								duration: 2000
							});
							uni.navigateTo({
								url: '/pages/vehicle_repair/booking/booking'
							})
						}
					}
				})
			},
			
		},

	};
</script>

<style>
	.container {
		padding: 30rpx;
		background-color: #fff;
	}

	.repair-type {
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.type-label {
		font-size: 32rpx;
		font-weight: bold;
		margin-right: 30rpx;
	}

	.radio-group {
		display: flex;
		align-items: center;
	}

	.radio-item {
		margin-left: 40rpx;
		display: flex;
		align-items: center;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
		/* border-bottom: 2rpx solid #eee; */
	}

	.from-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	/* 日期选择框样式优化 */
	.datetime-picker {
		flex: 1;
	}

	.label {
		display: inline-block;
		width: 160rpx;
		text-align: right;
		margin-right: 20rpx;
		font-size: 28rpx;
	}

	input {
		flex: 1;
		height: 70rpx;
		border: 2rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx; /* 统一输入框字体大小 */
	}
	
	/* 统一placeholder字体大小 */
	input::placeholder {
		font-size: 28rpx;
		color: #999;
	}
	
	/* 统一uni-easyinput的字体大小 */
	.uni-easyinput__content-input {
		font-size: 28rpx !important;
	}
	
	.uni-easyinput__content-input::placeholder {
		font-size: 28rpx !important;
		color: #999 !important;
	}
	
	/* 统一uni-data-picker的字体大小 */
	.uni-data-picker {
		font-size: 28rpx !important;
	}
	
	.uni-data-picker__input-text {
		font-size: 28rpx !important;
	}
	
	.uni-data-picker__input-text--placeholder {
		font-size: 28rpx !important;
		color: #999 !important;
	}

	.photo-section {
		margin-top: 40rpx;
	}

	.photo-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.photo-label {
		display: inline-block;
		width: 160rpx;
		text-align: right;
		margin-right: 20rpx;
		font-size: 28rpx;
	}

	.submit-btn {
		width: 100%;
		height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		border: none;
		border-radius: 8rpx;
		font-size: 32rpx;
		margin-top: 40rpx;
	}

	/* 全屏地图容器 */
	.fullscreen-map-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		z-index: 9999;
		background-color: #fff;
	}
	
	.fullscreen-map {
		width: 100%;
		height: 100%;
		/* 确保地图可以拖拽 */
		touch-action: manipulation;
		-webkit-user-select: none;
		user-select: none;
		-webkit-touch-callout: none;
		-webkit-tap-highlight-color: transparent;
	}
	
	.map-cancel-btn {
		position: absolute;
		top: 40rpx;
		right: 40rpx;
		z-index: 1000;
	}
	
	.cancel-btn {
		background-color: #ff4757;
		color: #fff;
		border: none;
		border-radius: 8rpx;
		padding: 10rpx 20rpx;
		font-size: 28rpx;
	}
	
	.map-tip {
		position: absolute;
		bottom: 100rpx;
		left: 50%;
		transform: translateX(-50%);
		background-color: rgba(0, 0, 0, 0.7);
		color: #fff;
		padding: 20rpx 40rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		z-index: 1000;
		text-align: center;
	}
</style>